import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.niws.client.http.RestClient;

import java.io.InputStream;
import java.io.SequenceInputStream;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.Semaphore;

public class RibbonClientDemo {

    public static void main(String[] args) throws Exception {

        ConfigurationManager.loadPropertiesFromResources("client.properties");
        System.out.println(ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers"));
        RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client");

        HttpRequest request = HttpRequest.newBuilder().uri(new URI("/format/date"))
                .queryParam("param1", "abc")
                .queryParam("param2","100")
                .build();
        for (int i = 0; i < 20000; i++) {
            HttpResponse response = client.executeWithLoadBalancer(request);
            System.out.println("Status for URI:" + response.getRequestedURI() + " is :" + response.getStatus());
            InputStream inputStream = response.getInputStream();
            int size = inputStream.available();
            byte[] bytes = new byte[size];
            inputStream.read(bytes);
            String result = new String(bytes,"utf-8");
            System.out.println(result);
            inputStream.close();
            ObjectMapper objectMapper = new ObjectMapper();
            Map m = objectMapper.readValue(result, Map.class);
            System.out.println("age:"+m.get("age")+",name:"+m.get("name")+",date:"+m.get("date"));
            Thread.currentThread().sleep(888);
        }
       /* ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();
        System.out.println(lb.getLoadBalancerStats());
        ConfigurationManager.getConfigInstance().setProperty("sample-client.ribbon.listOfServers", "www.baidu.com:80,www.linkedin.com:80");
        System.out.println("changing servers ...");
        Thread.sleep(3000);
        for (int i = 0; i < 20; i++) {
            HttpResponse response = client.executeWithLoadBalancer(request);
            System.out.println("Status for URI:" + response.getRequestedURI() + " is :" + response.getStatus());
        }
        System.out.println(lb.getLoadBalancerStats());*/

        client.shutdown();
    }
}
